<template>
  <div ref="chart" style="width: 100%; height: 400px;"></div>
</template>

<script>
import * as echarts from 'echarts'
import { getPetTypeData } from '@/api/analysis'

export default {
  name: 'PetTypeChart',
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.fetchData()
    window.addEventListener('resize', this.resizeHandler)
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.chart.setOption({
        title: {
          text: '总宠物数：0',
          right: '5%',
          top: '5%'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'middle'
        },
        series: [
          {
            name: '宠物类型',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c}只 ({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            }
          }
        ]
      })
    },
    async fetchData() {
      try {
        const res = await getPetTypeData()
        const { petTypes, totalPets } = res.data
        
        // 将Map转换为饼图数据格式
        const chartData = Object.entries(petTypes).map(([name, value]) => ({
          name,
          value
        }))

        this.chart.setOption({
          title: {
            text: `总宠物数：${totalPets}只`
          },
          series: [{
            data: chartData
          }]
        })
      } catch (error) {
        console.error('加载宠物类型数据失败:', error)
      }
    },
    refreshData() {
      this.fetchData()
    },
    resizeHandler() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      window.removeEventListener('resize', this.resizeHandler)
    }
  }
}
</script>
